package com.zhj.test.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * 说明
 * 1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
 * 2. httpObject 客户端和服务端相互通讯的数据封装成HttpObject
 * @author zhj
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // System.out.println(new String(msg.array(), CharsetUtil.UTF_8));
        System.out.println("服务端接收的数据 " + new String(msg.getContent(), CharsetUtil.UTF_8));
        System.out.println("服务端接收的数据长度 " + msg.getLen());
        System.out.println("服务器接收到的消息量：" + (++this.count));

        String responseContent = UUID.randomUUID().toString();
        int len = responseContent.getBytes(StandardCharsets.UTF_8).length;
        MessageProtocol messageProtocol = new MessageProtocol(len, responseContent.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(messageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务器异常：" + cause.getMessage());
        ctx.close();
    }
}
